package com.fauks.study.msweb.controller;

import com.fauks.study.msweb.dao.DepartmentDao;
import com.fauks.study.msweb.dao.EmployeeDao;
import com.fauks.study.msweb.entities.Department;
import com.fauks.study.msweb.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 员工crud操作
 */
@Controller
public class EmpController {

    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping("/login")
    public String login(String username, String password, Map<String, Object> result, HttpSession session) {
        System.out.println(username + "::" + password);
        if (!StringUtils.isEmpty(username) && "1".equals(password)) {
            //存入session
            session.setAttribute("user", username);
            return "redirect:/main.html";
        } else {
            result.put("msg", "用户名密码错误");
            return "login";
        }
    }

    //员工列表
    @GetMapping("/emps")
    public String list(Model model) {
        Collection<Employee> employeeList = employeeDao.getAll();
        model.addAttribute("emps", employeeList);
        return "emp/list";
    }

    //跳转到员工添加页面
    @GetMapping("/emp")
    public String addEmpView(Model model) {
        //查询所有部门
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);
        return "emp/add";
    }

    //添加员工
    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }
}
